#!/usr/bin/env node
const superagent = require('superagent');
const fs = require('fs-extra');
const os = require('os');
const _ = require('lodash');
const path = require('path');
let debug = false;
let emr = false;

function httpPost (data = {}) {
  data.authority = '__xunshu__';
  const url = !emr ? 'https://ydyxkfyy.huashan.org.cn:5932/cdr/test' : 'http://api.ifufan.com:12201/xs_etl/apis/emr/sql/';
  debug && console.log('[httpPost] send:', url, data);
  return new Promise(resolve => {
    superagent.post(url)
    .set({ 'Content-Type': `application/json;charset=UTF-8` })
    .send(data)
    .end((error, res) => {
      error && console.log('error:', error);
      if (!error && res.statusCode === 200) {
        debug && console.log('[httpPost] receive:', url, res.body);
        return resolve(res.body);
      } else {
        resolve();
      }
    });
  });
}
async function queryRemoteSQL (sql) {
  console.log('[sql]:', sql);
  const data = await httpPost({ sql });
  if (!data || data.message) {
    data && console.log('[error]:', data.message);
    return {};
  } else {
    let list = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8').split(/\n/) : [];
    list = _.reverse(list);
    list.unshift(sql);
    list = _.uniq(list);
    list = _.reverse(list);
    fs.writeFileSync(logFile, list.join('\n'), 'utf-8');
    return data.result;
  }
}
async function queryList (sql) {
  let result;
  if (global.cdrDb) {
    result = isScreen ? await screenDb.query(sql) : await cdrDb.query(sql);
  } else {
    result = await queryRemoteSQL(sql);
  }
  return result.recordset || [];
}
async function queryOne (sql) {
  const list = await queryList(sql);
  return list[0];
}
const logFile = path.join(os.homedir(), '.xn_history', '.xn_cdr_history');
async function main () {
  let list = process.argv.slice(2);
  debug = _.includes(list, '-d');
  if (debug) {
    list = _.reject(list, o=>o==='-d');
  }
  emr = _.includes(list, '-emr');
  if (emr) {
    list = _.reject(list, o=>o==='-emr');
  }
  const param1 = list[0];
  const param2 = list[1];
  const param3 = list[2];
  let sql = param1;
  if (!param1 || param1 === '-h' || param1 === '--help') {
    console.log('Usage: ');
    console.log('     xdr sql [type]: 1 one else list');
    console.log('     xdr -c table [where]: show count');
    console.log('     xdr -t table [where]: show top 1');
    console.log('     xdr -l: show history');
    console.log('     xdr -d sql: set debug');
    console.log('     xdr -emr sql: use emr');
    console.log();
    console.log('     xdr -pv pv: get idNo by pv');
    console.log('     xdr -idNo idNo: get pvs by idNo');
    console.log('     xdr -opv pv: get idNo by pv in op');
    console.log('     xdr -oidNo idNo: get pvs by idNo in op');
    console.log();
    process.exit();
  }
  let ret;
  if (param1 === '-l') {
    return console.log(fs.readFileSync(logFile, 'utf-8'));
  }
  if (param1 === '-c') {
    sql = `select count(*) as count from ${param2} ${ param3 || "where LastUpdateDateTime>='2021-01-01 00:00:00'"}`;
    ret = await queryOne(sql);
  } else if (param1 == '-t') {
    sql = `select top 1 * from ${param2} ${ param3 || "where LastUpdateDateTime>='2021-01-01 00:00:00'"}`;
    ret = await queryOne(sql);
  } else if (param1 == '-pv') {
    sql = `SELECT a.IDNumber FROM HDC_ADT.dbo.ADT_IP_PatientAcount a with(nolock), HDC_ADT.dbo.ADT_IP_Encounter b with(nolock) WHERE b.VisitNumber='${param2}' AND a.PatientID=b.PatientID`;
    ret = await queryList(sql);
  } else if (param1 == '-opv') {
    sql = `SELECT a.IDNumber FROM HDC_ADT.dbo.ADT_OP_PatientAcount a with(nolock), HDC_ADT.dbo.ADT_OP_Encounter b with(nolock) WHERE b.VisitNumber='${param2}' AND a.PatientID=b.PatientID`;
    ret = await queryList(sql);
  } else if (param1 == '-idNo') {
    sql = `select a.VisitNumber from ADT_IP_Encounter a with(nolock), ADT_IP_PatientAcount b with(nolock) WHERE b.IDNumber='${param2}' and a.PatientID=b.PatientID`;
    ret = await queryList(sql);
  } else if (param1 == '-oidNo') {
    sql = `select a.VisitNumber from ADT_OP_Encounter a with(nolock), ADT_OP_PatientAcount b with(nolock) WHERE b.IDNumber='${param2}' and a.PatientID=b.PatientID`;
    ret = await queryList(sql);
  } else {
    ret = await queryList(sql);
  }
  console.log(JSON.stringify(ret, null, 2));
}
main();
